package com.dawnClass.controller;

import com.dawnClass.service.UploadImageService;
import com.dawnClass.util.JsonTool;
import com.dawnClass.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class UploadController {

    @Resource
    @Autowired
    private UploadImageService uploadImageService;

    @PostMapping("UEditor/image/uploadFile")
    private String upLoadImage(@RequestParam("upfile") MultipartFile multipartFile) throws IOException {

        // 获取文件的名称
        String fileName = multipartFile.getOriginalFilename();

        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = StringUtil.getRandomImgName(fileName);
//        System.out.println("上传到七牛云的图片链接:" + imgName);
//        String imgName = multipartFile.getName();
        System.out.println("图片名称:"+imgName);

        if (!multipartFile.isEmpty()) {

            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
            System.out.println(inputStream);

            String path = uploadImageService.uploadQNImg(inputStream, imgName);
            System.out.print("七牛云返回的图片链接:" + path);
            Map<String,Object> map = new HashMap<>();
            map.put("name",imgName);
            map.put("size",multipartFile.getSize());
            map.put("state","SUCCESS");
            map.put("url",path);
            String json = JsonTool.toJson(map);
            System.out.println(json);
            return json;
        }
        return "上传失败";
    }

}